package com.zhugang.week03;

import java.util.Stack;

/**
 * @program algorithms
 * @description: dailyTemperatures
 * @author: chanzhugang
 * @create: 2022/06/05 17:55
 */
public class DailyTemperatures2 {

    /**
     * 739. 每日温度
     *
     * @param temperatures
     * @return
     */
    public int[] dailyTemperatures(int[] temperatures) {
        // 暴力求解：两层for循环
        int n = temperatures.length;
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (temperatures[j] > temperatures[i]) {
                    res[i] = j - i;
                    break;

                }
            }
        }
        return res;
    }

    public int[] dailyTemperatures2(int[] temperatures) {
        int n = temperatures.length;
        int[] res = new int[n];
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
                Integer idx = stack.peek();
                res[idx] = i - idx;
                stack.pop();
            }
            // 栈存储的是下标
            stack.push(i);
        }
        return res;
    }
}